package com.edoomath.api.servcice.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.persistence.GenericDaoSupport;
import com.demo2do.core.persistence.annotation.Dao;
import com.edoomath.api.dao.UserDao;
import com.edoomath.api.servcice.PaymentCallbackService;
import com.edoomath.entity.recharge.RechargeOrder;
import com.edoomath.entity.trade.PaymentRequest;
import com.edoomath.entity.user.ConsumeTag;
import com.edoomath.entity.user.ConsumeType;
import com.edoomath.entity.user.User;
import com.edoomath.entity.user.UserConsumeRecorder;
import com.edoomath.entity.user.UserWallet;

/**
 * 
 * @author mohanlan
 *
 */
@Service("paymentCallbackService")
public class PaymentCallbackServiceImpl implements PaymentCallbackService {
	
	@Autowired
    private GenericDaoSupport genericDaoSupport;
	
	@Dao
	private UserDao userDao;

	/*
	 * (non-Javadoc)
	 * @see com.edoomath.appserver.servcice.PaymentCallbackService#pay(com.edoomath.entity.trade.PaymentRequest, java.lang.String, java.lang.String, java.lang.String, int)
	 */
	public RechargeOrder pay(PaymentRequest paymentRequest, String orderCode, String payCode, String payTime, int amount) {
		
		RechargeOrder rechargeOrder = this.loadOrder(orderCode);
		
		if(rechargeOrder == null) {
			throw new BusinessException("支付回调订单数据有误");
		}
		
        // 1. update payment request
		genericDaoSupport.update(paymentRequest.paid(payCode));
		
		// 2. update recharge order
		genericDaoSupport.update(rechargeOrder.paid());
		
		// 3. update userWallet
		User user = rechargeOrder.getUser();
		UserWallet userWallet = userDao.loadWallet(user);
		genericDaoSupport.update(userWallet);
		
		// 4. create new user consume record here
		UserConsumeRecorder consumeRecorder = new UserConsumeRecorder(user, "课时充值", amount, ConsumeType.IN, ConsumeTag.RECHARGE_IN);
		genericDaoSupport.save(consumeRecorder.initliaze());
		
		return rechargeOrder;
	}
	
	/**
     * 
     * @param code
     * @return
     */
    private RechargeOrder loadOrder(String code) {
        return genericDaoSupport.searchForObject("FROM RechargeOrder WHERE disabled = false AND paymentStatus = 'PENDING' AND code = :code", "code", code, RechargeOrder.class);
    }

}
